package com.zhangyj.util;

import java.lang.reflect.Method;

import com.zhangyj.entitis.TreeItem;


public class BeanParse {

	private final static char[] get = new char[] { 'g', 'e', 't' };
	private final static char[] set = new char[] { 's', 'e', 't' };

	public static String getGetMethod(String name) {
		return getMethod(get, name);
	}

	/**
	 * 
	 * @param name
	 * @return
	 */
	public static String getSetMethod(String name) {
		return getMethod(set, name);
	}

	/**
	 * 
	 * @param name
	 * @param offset
	 * @param length
	 * @return
	 */
	public static String getMethod(char[] fixed, String name) {
		char[] cs = new char[name.length() + 3];
		System.arraycopy(fixed, 0, cs, 0, 3);
		name.getChars(0, name.length(), cs, 3);
		// System.arraycopy(name, offset, cs, 3, length);
		char c = cs[3];
		if (c >= 'a' && c <= 'z') {
			c = (char) (c - 32);
			cs[3] = c;
		}
		return new String(cs);
	}

	/**
	 * 给对象的一个属性赋值。
	 * 
	 * @param obj
	 *            要赋值的对象
	 * @param name
	 *            属性名称
	 * @param val
	 *            值
	 * @throws Exception
	 */
	public static void setValue(Object obj, String name, Object val) throws Exception {

		Method m = obj.getClass().getMethod(getSetMethod(name), val.getClass());
		m.invoke(obj, val);
	}

	/**
	 * 获取一个对象的属性值
	 * 
	 * @param obj
	 *            对象
	 * @param name
	 *            属性名称
	 * @return 属性值
	 * @throws Exception
	 */
	public static Object getValue(Object obj, String name) throws Exception {
		if (name.indexOf('.') == -1) {
			Method m = obj.getClass().getMethod(getGetMethod(name));
			return m.invoke(obj);
		}

		String[] fields = name.split("\\.");
		for (int i = 0; i < fields.length; i++) {
			Method m = obj.getClass().getMethod(getGetMethod(fields[i]));
			obj = m.invoke(obj);
		}
		return obj;
	}

	public static void main(String[] args) {
		Object obj = new TreeItem();

		try {

			long a = System.currentTimeMillis();
			for (int i = 0; i < 100000; i++) {
				setValue(obj, "code", "helloworld");
			}
			System.out.println(System.currentTimeMillis() - a);
			a = System.currentTimeMillis();
			for (int i = 0; i < 100000; i++) {
				getValue(obj, "code");
			}
			System.out.println(getValue(obj, "code"));
			System.out.println(System.currentTimeMillis() - a);

		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
	}

}
